package com.hmdp.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.hmdp.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;@Override
    public Result queryList() {
        String key = RedisConstants.CANCEL_SHOPTYPE_KEY;
        // 1.从redis查询商铺类型缓存
        List<String> shopTypeList = stringRedisTemplate.opsForList()
                .range(key, 0, -1);

        // 2. 判断是否存在
        if (CollUtil.isNotEmpty(shopTypeList)) {
            List<ShopType> typeList = JSONUtil.toList(shopTypeList.toString(), ShopType.class);
                    return Result.ok(typeList);
        }

        // 4.不存在，从数据库查询
        List<ShopType> typeList = query().orderByAsc("sort").list();

        // 5.数据库中不存在，返回错误
        if (CollUtil.isEmpty(typeList)) {
            return Result.fail("店铺类型不存在");
        }

        // 6.存在，写入redis
        // 将 typeList 中的每个 ShopType 对象转换为 JSON 字符串，并收集到一个新的 List 中
        List<String> shopTypeStringList = typeList.stream().map(JSONUtil::toJsonStr).collect(Collectors.toList());
        stringRedisTemplate.opsForList().rightPushAll(
                key,
                shopTypeStringList
        );

        // 7.返回
        return Result.ok(typeList);
    }

}
